package com.donger.common.security.filter;

import cn.hutool.core.util.StrUtil;
import com.donger.common.core.constant.SecurityConstants;
import com.donger.common.security.entity.ValidateCodeType;
import com.donger.common.security.exception.ValidateCodeException;
import com.donger.common.security.validate.BuildValidateCodeProcessor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@Component
@Slf4j
public class ValidateCodeFilter extends OncePerRequestFilter implements InitializingBean {

    @Autowired
    private AuthenticationFailureHandler authenticationFailureHandler;

    private Map<String, ValidateCodeType> urlMap = new HashMap<>();

    private AntPathMatcher pathMatcher = new AntPathMatcher();

    @Autowired
    private BuildValidateCodeProcessor buildValidateCodeProcessor;

    @Override
    public void afterPropertiesSet() throws ServletException {
        super.afterPropertiesSet();
        urlMap.put(SecurityConstants.DEFAULT_PARAMETER_CODE_SMS_URL, ValidateCodeType.SMS);
        urlMap.put(SecurityConstants.DEFAULT_PARAMETER_CODE_IMAGE_URL, ValidateCodeType.IMAGE);

    }

    /**
     * 请求过滤器
     *
     * @param req
     * @param res
     * @param filterChain
     * @throws ServletException
     * @throws IOException
     */


    @Override
    protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain filterChain) throws ServletException, IOException {
        // 统一判断 验证码

        ValidateCodeType type = getValidateCodeType(req);
        if (type != null) {
            log.debug("校验请求（" + req.getRequestURI() + ")中额验证码，类型为" + type);
            try {
                buildValidateCodeProcessor.build(type).validate(req);
            } catch (ValidateCodeException e) {
                authenticationFailureHandler.onAuthenticationFailure(req, res, e);
                return;
            }
        }
        filterChain.doFilter(req, res);
    }


    /**
     * 获取校验码的类型，如果当前请求不需要校验，则返回null
     *
     * @param request
     * @return
     */
    private ValidateCodeType getValidateCodeType(HttpServletRequest request) {
        log.debug("校验请求类型，请求地址为" + request.getRequestURI());
        ValidateCodeType result = null;
        if (!StrUtil.equalsIgnoreCase(request.getMethod(), "get")) {
            Set<String> urls = urlMap.keySet();
            for (String url : urls) {
                if (pathMatcher.match(url, request.getRequestURI())) {
                    result = urlMap.get(url);
                }
            }
        }

        return result;
    }
}
